package com.study.manage.service;

import com.study.manage.entity.PermissionVO;
import com.study.manage.pojo.Permission;
import com.study.manage.pojo.Role;
import com.study.manage.repository.EntityManagerRepository;
import com.study.manage.repository.PermissionRepository;
import com.study.manage.repository.RoleRepository;
import com.study.manage.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * @项目名称：study.manage
 * @包名：com.study.manage.service
 */
@Service
public class AuthServiceImpl implements AuthService {
	private static final Logger logger = LoggerFactory
			.getLogger(AuthServiceImpl.class);


	@Autowired
	private RoleRepository roleRepository;
	@Autowired
	private PermissionRepository permissionRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private EntityManagerRepository entityManagerRepository;

	@Override
	public void addPermission(Permission permission) {
		this.permissionRepository.save(permission);
	}

	@Override
	public List<Permission> permList() {
		return this.permissionRepository.findAll();
	}

	@Override public int updatePerm(Permission permission) {
		return this.permissionRepository.update(permission);
	}

	@Override public Permission getPermission(int id) {
		return this.permissionRepository.findById(id).orElse(null);
	}

	@Override public String delPermission(int id) {
		//查看该权限是否有子节点，如果有，先删除子节点
		List<Permission> childPerm = this.permissionRepository.findByPid(id);
		if(null != childPerm && childPerm.size()>0){
			return "删除失败，请您先删除该权限的子节点";
		}
		this.permissionRepository.deleteById(id);
		return "ok";
	}

	@Override
	public List<Role> roleList() {
		return getRoles();
	}

	@Override public List<PermissionVO> findPerms() {
		return this.permissionRepository.findPerms();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=30000,rollbackFor={RuntimeException.class, Exception.class})
	public String addRole(Role role, String permIds) {
		this.roleRepository.save(role);
		int roleId=role.getId();
		String[] arrays=permIds.split(",");
		logger.debug("权限id =arrays="+arrays.toString());
		setRolePerms(roleId, arrays);
		return "ok";
	}

	@Override public Role findRoleAndPerms(Integer id) {
		return this.roleRepository.findById(id).orElse(null);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=30000,rollbackFor={RuntimeException.class, Exception.class})
	public String updateRole(Role role, String permIds) {
		int roleId=role.getId();
		String[] arrays=permIds.split(",");
		logger.debug("权限id =arrays="+arrays.toString());
		//1，更新角色表数据；
		int num=this.roleRepository.update(role);
		if(num<1){
			//事务回滚
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "操作失败";
		}
		//2，删除原角色权限；
		batchDelRolePerms(roleId);
		//3，添加新的角色权限数据；
		setRolePerms(roleId, arrays);
		return "ok";
	}



	@Override
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=30000,rollbackFor={RuntimeException.class, Exception.class})
	public String delRole(int id) {
		//1.删除角色对应的权限
		batchDelRolePerms(id);
		//2.删除角色
		this.roleRepository.deleteById(id);

		return "ok";
	}

	@Override
	public List<Role> getRoles() {
		//TODO 根据部门和权限等级限制角色显示
		return this.roleRepository.findAll();
	}

	@Override
	public List<Role> getRoleByUser(Integer userId) {
		return this.userRepository.getRoleByUserId(userId);
	}

	@Override
	public List<Permission> findPermsByRoleId(Integer id) {
		return this.roleRepository.findPermsByRole(id);
	}

	@Override
	public List<PermissionVO> getUserPerms(Integer id) {
		return this.entityManagerRepository.findPermsByUserId(id);
	}

	/**
	 * 批量删除角色权限中间表数据
	 * @param roleId
	 */
	private void batchDelRolePerms(int roleId) {
//		List<RolePermissionKey> rpks=this.rolePermissionMapper.findByRole(roleId);
//		if(null!=rpks && rpks.size()>0){
//			for (RolePermissionKey rpk : rpks) {
//				this.rolePermissionMapper.deleteByPrimaryKey(rpk);
//			}
//		}
		this.roleRepository.batchDelRolePerms(roleId);
	}

	/**
	 * 给当前角色设置权限
	 * @param roleId
	 * @param arrays
	 */
	private void setRolePerms(int roleId, String[] arrays) {
//		for (String permid : arrays) {
//			RolePermissionKey rpk=new RolePermissionKey();
//			rpk.setRoleId(roleId);
//			rpk.setPermitId(Integer.valueOf(permid));
//			this.rolePermissionMapper.insert(rpk);
//		}
		for (String permid : arrays) {
			this.roleRepository.saveRolePermission(roleId,Integer.valueOf(permid));
		}
	}
}
